#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
请求模块相关路由
"""

import logging
import json
from flask import Blueprint, request, jsonify
from base.services.request_service import RequestService

logger = logging.getLogger(__name__)

# 创建蓝图
request_bp = Blueprint('request', __name__)

@request_bp.route('/definitions', methods=['POST'])
def create_request_definition():
    """创建请求定义"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取请求定义信息
        name = data.get('name')
        description = data.get('description')
        request_method = data.get('request_method')
        request_url = data.get('request_url')
        request_headers = data.get('request_headers', {})
        request_body = data.get('request_body')

        # 验证必填字段
        if not name:
            return jsonify({"error": "请求名称不能为空"}), 400
        if not request_method:
            return jsonify({"error": "请求方法不能为空"}), 400
        if not request_url:
            return jsonify({"error": "请求URL不能为空"}), 400

        # 创建请求定义
        definition_id = RequestService.create_request_definition(
            name, request_method, request_url, description, request_headers, request_body
        )

        # 获取创建的请求定义详情
        definition = RequestService.get_request_definition_by_id(definition_id)

        return jsonify(definition), 201

    except Exception as e:
        logger.error(f"创建请求定义失败: {e}")
        return jsonify({"error": f"创建请求定义失败: {str(e)}"}), 500

@request_bp.route('/definitions', methods=['GET'])
def get_request_definitions():
    """获取请求定义列表"""
    try:
        # 获取分页参数
        page = int(request.args.get('page', 1))
        page_size = int(request.args.get('page_size', 10))

        # 获取请求定义列表
        result = RequestService.get_request_definitions(page, page_size)

        return jsonify(result), 200

    except Exception as e:
        logger.error(f"获取请求定义列表失败: {e}")
        return jsonify({"error": f"获取请求定义列表失败: {str(e)}"}), 500

@request_bp.route('/definitions/<definition_id>', methods=['GET'])
def get_request_definition(definition_id):
    """获取请求定义详情"""
    try:
        # 获取请求定义详情
        definition = RequestService.get_request_definition_by_id(definition_id)

        if not definition:
            return jsonify({"error": "请求定义不存在"}), 404

        return jsonify(definition), 200

    except Exception as e:
        logger.error(f"获取请求定义详情失败: {e}")
        return jsonify({"error": f"获取请求定义详情失败: {str(e)}"}), 500

@request_bp.route('/definitions/<definition_id>', methods=['PUT'])
def update_request_definition(definition_id):
    """更新请求定义"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取请求定义信息
        name = data.get('name')
        description = data.get('description')
        request_method = data.get('request_method')
        request_url = data.get('request_url')
        request_headers = data.get('request_headers')
        request_body = data.get('request_body')

        # 更新请求定义
        success = RequestService.update_request_definition(
            definition_id, name, description, request_method, request_url, request_headers, request_body
        )

        if not success:
            return jsonify({"error": "请求定义不存在"}), 404

        # 获取更新后的请求定义详情
        definition = RequestService.get_request_definition_by_id(definition_id)

        return jsonify(definition), 200

    except Exception as e:
        logger.error(f"更新请求定义失败: {e}")
        return jsonify({"error": f"更新请求定义失败: {str(e)}"}), 500

@request_bp.route('/definitions/<definition_id>', methods=['DELETE'])
def delete_request_definition(definition_id):
    """删除请求定义"""
    try:
        # 删除请求定义
        success = RequestService.delete_request_definition(definition_id)

        if not success:
            return jsonify({"error": "请求定义不存在"}), 404

        return jsonify({"message": "请求定义删除成功"}), 200

    except Exception as e:
        logger.error(f"删除请求定义失败: {e}")
        return jsonify({"error": f"删除请求定义失败: {str(e)}"}), 500

@request_bp.route('/definitions/<definition_id>/execute', methods=['POST'])
def execute_request(definition_id):
    """执行请求"""
    try:
        # 执行请求
        result = RequestService.execute_request_sync(definition_id)

        if not result:
            return jsonify({"error": "请求定义不存在"}), 404

        if "error" in result:
            return jsonify({
                "error": f"请求执行失败: {result['error']}",
                "request": result["request"],
                "duration_ms": result["duration_ms"]
            }), 500

        return jsonify(result), 200

    except Exception as e:
        logger.error(f"执行请求失败: {e}")
        return jsonify({"error": f"执行请求失败: {str(e)}"}), 500

@request_bp.route('/intercept/start', methods=['POST'])
def start_intercept():
    """开始拦截"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取服务ID
        service_id = data.get('service_id')
        if not service_id:
            return jsonify({"error": "服务ID不能为空"}), 400

        # 获取拦截方向
        direction = data.get('direction', 'output')  # 默认只拦截出站流量
        if direction not in ['input', 'output', 'both']:
            return jsonify({"error": "拦截方向无效，必须是 'input', 'output' 或 'both'"}), 400

        # 调用拦截组件的拦截服务
        import requests
        import os

        # 使用环境变量或默认值获取拦截组件的服务地址
        intercept_host = os.getenv('INTERCEPT_HOST', 'kube-relayer-intercept')
        intercept_port = os.getenv('INTERCEPT_PORT', '5555')

        response = requests.post(
            f'http://{intercept_host}:{intercept_port}/api/intercept_control/iptables/setup',
            json={
                'service_id': service_id,
                'direction': direction
            }
        )

        if response.status_code != 200:
            return jsonify({"error": f"启动拦截服务失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"开始拦截失败: {e}")
        return jsonify({"error": f"开始拦截失败: {str(e)}"}), 500

@request_bp.route('/intercept/stop', methods=['POST'])
def stop_intercept():
    """停止拦截"""
    try:
        data = request.json
        if not data:
            return jsonify({"error": "请求体不能为空"}), 400

        # 获取服务ID
        service_id = data.get('service_id')
        if not service_id:
            return jsonify({"error": "服务ID不能为空"}), 400

        # 调用拦截组件的拦截服务
        import requests
        import os

        # 使用环境变量或默认值获取拦截组件的服务地址
        intercept_host = os.getenv('INTERCEPT_HOST', 'kube-relayer-intercept')
        intercept_port = os.getenv('INTERCEPT_PORT', '5555')

        response = requests.post(
            f'http://{intercept_host}:{intercept_port}/api/intercept_control/iptables/remove',
            json={'service_id': service_id}
        )

        if response.status_code != 200:
            return jsonify({"error": f"停止拦截服务失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"停止拦截失败: {e}")
        return jsonify({"error": f"停止拦截失败: {str(e)}"}), 500

@request_bp.route('/intercept/list', methods=['GET'])
def list_intercepts():
    """列出拦截规则"""
    try:
        # 调用拦截组件的拦截服务
        import requests
        response = requests.get('http://localhost:5556/api/intercept_control/iptables/list')

        if response.status_code != 200:
            return jsonify({"error": f"列出拦截规则失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"列出拦截规则失败: {e}")
        return jsonify({"error": f"列出拦截规则失败: {str(e)}"}), 500

@request_bp.route('/intercept/clear', methods=['POST'])
def clear_intercepts():
    """清除所有拦截规则"""
    try:
        # 调用拦截组件的拦截服务
        import requests
        response = requests.post('http://localhost:5556/api/intercept_control/iptables/clear')

        if response.status_code != 200:
            return jsonify({"error": f"清除拦截规则失败: {response.text}"}), 500

        # 返回结果
        return jsonify(response.json()), 200

    except Exception as e:
        logger.error(f"清除拦截规则失败: {e}")
        return jsonify({"error": f"清除拦截规则失败: {str(e)}"}), 500
